{% extends 'base.twig' %} 

{% block extraHead %}
<style>
.table { width: auto !important; }
.table select,option,input,textarea { font-family: Trebuchet MS; }
.table td { cursor: move; }
input[type=submit] { float: right; margin-left: 5px; }
select { padding: 6px; }
.column { border: 1px solid #ddd; padding: 10px 40px; margin-bottom: 10px; background: -moz-linear-gradient(0px 100% 90deg, rgba(0, 0, 0, 0.05), rgba(0, 0, 0, 0)) repeat scroll 0 0 #eee; cursor: move; min-width: 1024px; }
.column .box { width: 30%; display: inline-block; padding: 5px 10px; }
.column .box select { width: 100%; }
.column .myTitle { padding-left: 10px; float: none; display: inline-block; width: 200px; height: 80px; }
.column .myTitle input, .column .myTitle a, .column .myTitle select { visibility: hidden; }
.column .selected input, .column .selected a, .column .selected select { visibility: visible !important; }
.column .myTitle select { padding: 2px 6px; width: 90%; }
.tab-control { background: -moz-linear-gradient(0px 100% 90deg, rgba(0, 0, 0, 0.05), rgba(0, 0, 0, 0)) repeat scroll 0 0 #fff; }
#notForSortable, #notForList, #notForDetail { border: 1px solid #ddd; background: #fff; display: inline-block; padding: 5px 10px; }
</style>
{% endblock %} 

{% block contentContainer %}
	<div class="container">
		<div class="example" style="min-width: 1200px;">
			<form action="" method="POST" autocomplete="off" enctype="application/x-www-form-urlencoded">
				<input id="obj" name="obj" type="hidden" />
				
				<fieldset>
					<legend>{{ model ? 'Model #' ~ model.id : 'New model' }}</legend>
					<label>Name</label>
					<div class="input-control text" data-role="input-control">
						<input id="name" name="name" onchange="setValue('name',	$(this).val())" type="text" placeholder="type text" />
						<button class="btn-clear" tabindex="-1"></button>
					</div>
					
					<div class="input-control switch" data-role="input-control">
						<label class="inline-block" style="margin-right: 20px">Visible&nbsp;<input id="visible" name="visible" onclick="setValue('visible', this.checked ? 1 : 0);" type="checkbox" checked="checked" /> <span class="check"></span></label>
						<label class="inline-block" style="margin-right: 20px">Permission&nbsp;
							<select id="permission" name=permission onchange="setValue('permission', $(this).val());" >
								<option value="0">User</option>
								<option value="1">Admin</option>
							</select>
						</label>
						<label class="inline-block" style="margin-right: 20px">Under the section of&nbsp;
							<select id="type" name="type" onchange="setValue('type', $(this).val());" >
								<option value="1">Custom models</option>
								<option value="0">Built-in models</option>
							</select>
						</label>
						<label class="inline-block" style="margin-right: 20px">ID field&nbsp;<select id="idField" name="idField" onchange="setValue('idField', $(this).val());" ></select></label>
					</div>
					
					<br />
	
					<div class="input-control switch" data-role="input-control" id="notForInvisible">
						<label class="inline-block" style="margin-right: 20px">Using&nbsp;
							<select id="resortable" name="resortable" onchange="setValue('resortable', $(this).val());" >
								<option value="0">Pagination</option>
								<option value="1">Drag & drop sort</option>
							</select>
						</label>	
						<span id="notForSortable">
							<label class="inline-block" style="margin-right: 20px">Items per page&nbsp;<input id="numPerPage" name="numPerPage" style="width: 30px;" type="text" value="" /></label> 
							<label class="inline-block" style="margin-right: 20px">Default sort by&nbsp;<select id="defaultSortBy" name="defaultSortBy" onchange="setValue('defaultSortBy', $(this).val());" ></select></label>
						</span>
					</div>
					
					<br />
	
					<div class="input-control switch" data-role="input-control">
						<label class="inline-block" style="margin-right: 20px">Own list twig&nbsp;<input id="ownList" name="ownList" onclick="setValue('ownList', this.checked ? 1 : 0);" type="checkbox" checked="checked" /> <span class="check"></span></label>
						<span id="notForList" style="margin-right: 50px;">
							<label class="inline-block" style="margin-right: 20px">File name&nbsp;<input id="twigList" name="twigList" type="text" value="" onchange="setValue('twigList', $(this).val());" />.twig</label> 
						</span>
						
						<label class="inline-block" style="margin-right: 20px">Own detail twig&nbsp;<input id="ownDetail" name="ownDetail" onclick="setValue('ownDetail', this.checked ? 1 : 0);" type="checkbox" checked="checked" /> <span class="check"></span></label>
						<span id="notForDetail">
							<label class="inline-block" style="margin-right: 20px">File name&nbsp;<input id="twigDetail" name="twigDetail" type="text" value="" onchange="setValue('twigDetail', $(this).val());" />.twig</label>
						</span>
					</div>
					
					<br />
					<br />
	
					<button class="button bg-yellow" onclick="addColumn(event);">
						<i class="fa fa-plus-circle"></i>&nbsp;&nbsp;Add a column
					</button>
	
					<div>&nbsp;</div>
					
					<div>
						<ul id="columns" style="margin: 0; padding: 0;"></ul>
					</div>
	
					<div>&nbsp;</div>
	
					<a href="{{ returnURL }}">Back</a>
					<input type="submit" value="Submit & back" name="action">
					<input type="submit" value="Submit" name="action">
					{% if model %}<input type="submit" value="Remove" name="action" onclick="return confirm('Click OK to continue.');">{% endif %}
				</fieldset>
			</form>
		</div>
	</div>
{% endblock %} 


{% block extraFoot %}
<script>
	var _fields = {{ fields|json_encode|raw }};
	var _meta = {{ meta|json_encode|raw }};
	var _types = {{ types|json_encode|raw }};
	var _model = {% if model %}{{ model|json_encode|raw }}{% else %}null{% endif %};
	var _rank = {{ rank|raw }};
	var _mappings = [];
	
	$(function() {
		$("#numPerPage").spinner();
		$('#numPerPage').on('spinchange', function(event, ui) { setValue('numPerPage', $(event.target).val()); } );
		$('.ui-spinner-button').click(function() { setValue('numPerPage', $('#numPerPage').val()); });
		
		if (!_model) {
			_model = {
				id: null,
				name: '',
				rank: _rank,
				visible: 1,
				resortable: 0,
				numPerPage: 25,
				defaultSortBy: 'id',
				idField: 'id',
				columnsJson: '[]',
				type: {{ type }},
				permission: 0,
				ownList: 0,
				ownDetail: 0,
				twigList: '',
				twigDetail: '',
			};
		}
		_model.columnsJson = JSON.parse(_model.columnsJson);
		
		jQuery.grep(_fields, function(el) {
			if (jQuery.inArray(el, _meta) == -1) _mappings.push(el);
		});
		
		
		repaint();
	});

	function addColumn(ev) {
		ev.preventDefault();

		var available = [], used = [];
		for (var idx in _model.columnsJson) {
			var itm = _model.columnsJson[idx];
			used.push(itm.mapping);
		}
		
		jQuery.grep(_mappings, function(el) {
			if (jQuery.inArray(el, used) == -1) available.push(el);
		});

		if (available.length < 0) {
			alert('No more mapping fields available');
		}

		var column = {
			onList: 0,
			name: 'Label' + (_model.columnsJson.length + 1),
			field: 'field' + (_model.columnsJson.length + 1),
			type: {
				name: 'text',
				options: {},
			},
			constraints: [],
			mapping: available[0],
			defaultValue: '',
			which: 0,
		};
		
		for (var idx in _types) {
			var itm = _types[idx];
			if (idx == column.type.name) {
				for (var idx2 in itm) {
					var itm2 = itm[idx2];
					if (itm2.selected == 1) {
						column.type.options[idx2] = itm2.defaultValue; 
					}
				}
			}
		}
		_model.columnsJson.push(column);
		repaint();
	};

	function repaint() {
		_model.columnsJson = JSON.stringify(_model.columnsJson);
		$('#obj').val(JSON.stringify(_model));
		_model.columnsJson = JSON.parse(_model.columnsJson);

		var available = [], used = [];
		for (var idx in _model.columnsJson) {
			var itm = _model.columnsJson[idx];
			used.push(itm.mapping);
		}
		jQuery.grep(_mappings, function(el) {
			if (jQuery.inArray(el, used) == -1) available.push(el);
		});
		
		$('#defaultSortBy').empty();
		$('#defaultSortBy').append('<option>id</option>');
		for (var idx in _model.columnsJson) {
			var itm = _model.columnsJson[idx];
			$('#defaultSortBy').append('<option>' + itm.field + '</option>');
		}
		
		$('#idField').empty();
		$('#idField').append('<option>id</option>');
		for (var idx in _model.columnsJson) {
			var itm = _model.columnsJson[idx];
			$('#idField').append('<option>' + itm.field + '</option>');
		}

		$('#notForInvisible').css('display', _model.visible == 0 ? 'none' : '');
		$('#notForSortable').css('display', _model.resortable == 1 ? 'none' : '');
		$('#notForList').css('display', _model.ownList == 0 ? 'none' : '');
		$('#notForDetail').css('display', _model.ownDetail == 0 ? 'none' : '');
		
		$('#name').val(_model.name);
		$('#resortable').val(_model.resortable);
		$('#numPerPage').spinner('value', _model.numPerPage);
		$('#defaultSortBy').val(_model.defaultSortBy);
		$('#idField').val(_model.idField);
		$('#type').val(_model.type);
		$('#permission').val(_model.permission);
		$('#twigList').val(_model.twigList);
		$('#twigDetail').val(_model.twigDetail);
		
		if (_model.visible) {
			$('#visible').attr('checked', 'checked');
		} else {
			$('#visible').removeAttr('checked');
		}

		if (_model.ownList) {
			$('#ownList').attr('checked', 'checked');
		} else {
			$('#ownList').removeAttr('checked');
		}

		if (_model.ownDetail) {
			$('#ownDetail').attr('checked', 'checked');
		} else {
			$('#ownDetail').removeAttr('checked');
		}
		
		
		
		$('#columns').empty();
		for (var idx in _model.columnsJson) {
			var itm = _model.columnsJson[idx];

			var elem = $('<div class="column" data-idx="' + idx + '" />');
			$(elem).append(
				'<div class="tab-control" data-role="tab-control">' +
				
					'<ul class="tabs">' +
						'<li ' + ((itm.which == 0) ? 'class="active"' : '') + '><a class="columnTab" href="#p1' + idx + '">' + itm.name + '</a></li>' +
						'<li ' + ((itm.which == 1) ? 'class="active"' : '') + '><a class="columnTab" href="#p2' + idx + '">' + ucfirst(itm.type.name) + '</a></li>' +
						'<li ' + ((itm.which == 2) ? 'class="active"' : '') + '><a class="columnTab" href="#p3' + idx + '">Constraints</a></li>' +
						'<li class="place-right"><a href="#" class="remove"><i class="fa fa-times"></i></a></li>' +
					'</ul>' +
					
					'<div class="frames">' +
					
						'<div class="frame" id="p1' + idx + '">' +
						
							'<div class="box">' +
								'<label>Known as</label>' +
								'<div class="input-control text" data-role="input-control">' +
									'<input class="name" type="text" placeholder="type text" value="' + itm.name + '" />' +
									'<button class="btn-clear" tabindex="-1"></button>' +
								'</div>' +
							'</div>' +
							
							'<div class="box">' +
								'<label>Widget</label>' +
								'<div class="input-control text" data-role="input-control">' +
									'<select class="type" data-idx="' + idx + '"></select>' +
								'</div>' +
							'</div>' +
							
							'<div class="box">' +
									'<div class="input-control switch" data-role="input-control">' +
										'<label class="inline-block" style="margin-right: 20px">Listing&nbsp;' + 
											'<input class="onList" type="checkbox" ' + ((itm.onList == 1) ? 'checked="checked"' : '' )  + ' />' +
											'<span class="check"></span>' + 
										'</label>' + 
									'</div>' +
							'</div>' +
							
							'<div class="box">' +
								'<label>Field name</label>' +
								'<div class="input-control text" data-role="input-control">' +
									'<input class="field" type="text" placeholder="type text" value="' + itm.field + '" />' +
									'<button class="btn-clear" tabindex="-1"></button>' +
								'</div>' +
							'</div>' +
							
							'<div class="box">' +
								'<label>Mapping to</label>' +
								'<div class="input-control text" data-role="input-control">' +
									'<select class="mapping"></select>' +
								'</div>' +
							'</div>' +
							
							'<div class="box">' +
								'<label>Default value</label>' +
								'<div class="input-control text" data-role="input-control">' +
									'<input class="defaultValue" type="text" placeholder="type text" value="' + itm.defaultValue + '" />' +
									'<button class="btn-clear" tabindex="-1"></button>' +
								'</div>' +
							'</div>' +
							
						'</div>' +
						
						'<div class="frame" id="p2' + idx + '"></div>' +
						'<div class="frame" id="p3' + idx + '"></div>' +
						
					'</div>' +
				'</div>'
			);
			$('#columns').append(elem);
			
			for (var typeName in _types) {
				$(elem).find('.type').append('<option ' + ((typeName == itm.type.name) ? 'selected="selected"' : '') + ' value="' + typeName + '">' + ucfirst(typeName) + '</option>');

				if (typeName == itm.type.name) {
					var typeOptions = _types[typeName];
					for (typeOptionName in typeOptions) {
						var typeAttrs = typeOptions[typeOptionName];
						var optElem = $('<div data-name="' + typeOptionName + '" class="tile myTitle" />');
						$(optElem).append('<h4>' + ucfirst(typeOptionName) + '</h4>');
						
						
						$('#p2' + idx).append(optElem);
						if (typeAttrs['type'] == 'string' || typeAttrs['type'] == 'integer' || typeAttrs['type'] == 'mixed' || typeAttrs['type'] == 'boolean') {
							if (typeAttrs['options']) {
								var optSelect = $('<select class="myValue" />');
								$(optElem).append(optSelect);
								for (var idx2 in typeAttrs['options']) {
									var itm2 = typeAttrs['options'][idx2];
									$(optSelect).append('<option value="' + itm2 + '">' + itm2 + '</option>');
								}
							} else {
								if (typeAttrs['type'] == 'boolean') {
									$(optElem).append('<input type="hidden" class="myValue" value="true"></input>');
								} else {
									$(optElem).append('<input class="myValue" type="text" value="' + ((typeAttrs['default']) ? typeAttrs['default'] : '') + '" />');
								}
							}
						} else if (typeAttrs['type'] == 'array') {
							$(optElem).append('<a href="#" class="myValue">0 value</a>');
						}

						for (var idx2 in itm.type.options) {
							var itm2 = itm.type.options[idx2];
							if (idx2 == typeOptionName) {
								$(optElem).addClass('selected');
								$(optElem).find('.myValue').val(itm2);
							}
						}
					}
				}
			}

			$(elem).find('.mapping').append('<option>' + itm.mapping + '</option>');
			for (var idx2 in available) {
				var itm2 = available[idx2];
				$(elem).find('.mapping').append('<option>' + itm2 + '</option>');
			}
		}

		$('.tab-control').tabcontrol();
		$('.column :text, .column :checkbox, .column select:not(.type)').on('change', function(ev) { updateColumns(); });
		$('.column select.type').on('change', function(ev) {
			updateColumns();
			_model.columnsJson[$(this).data('idx')].type.options = {};
			for (var idx in _types) {
				var itm = _types[idx];
				if (idx == $(this).val()) {
					for (var idx2 in itm) {
						var itm2 = itm[idx2];
						if (itm2.selected == 1) {
							_model.columnsJson[$(this).data('idx')].type.options[idx2] = itm2.defaultValue; 
						}
					}
				}
			}
			repaint();
		});
		$('.columnTab').on('click', function(ev) { updateColumns(); });
		$('.column .remove').on('click', function(ev) { removeColumn($(this).parent().parent().parent().parent().data('idx')); });
		$('#columns').sortable({ stop: function(ev) { updateColumns(); }, });
		
		$('.btn-clear').on('click', function(ev) {
			ev.preventDefault();
			$(this).parent().find(':first-child').val('');
			$(this).parent().find(':first-child').select();
		});
		$('.myTitle').on('click', function(ev) {
			if ($(ev.target).hasClass('myTitle') || $(ev.target).is('h4')) {
				$(this).toggleClass('selected');
				updateColumns();
			}
		});
	};

	function removeColumn(index) {
		if (_model.defaultSortBy == _model.columnsJson[index].field) {
			_model.defaultSortBy = 'id';
		}
		_model.columnsJson.splice(index, 1);
		repaint();
	};

	function updateColumns() {
		_model.columnsJson = [];
		$.each($('.column'), function(key, value) {
			var column = {
				onList: $(value).find('.onList').is(':checked') ? 1 : 0,
				name: $(value).find('.name').val(),
				field: $(value).find('.field').val(),
				type: {
					name: $(value).find('.type').val(),
					options: {},
				},
				constraints: [],
				mapping: $(value).find('.mapping').val(),
				defaultValue: $(value).find('.defaultValue').val(),
				which: $(value).find('.tabs li.active').index(),
			};

			$.each($('#p2' + $(value).data('idx') + ' .myTitle'), function(key, value) {
				if ($(value).hasClass('selected')) {
					column.type.options[$(value).data('name')] = $(value).find('.myValue').val();
				}
			});
			_model.columnsJson.push(column);
			
		});
		repaint();
	};

	function setValue(attr, val) {
		if (attr == 'name') {
			if (!_model.id || _model.ownList == 0 || _model.twigList == '') {
				_model.twigList = val.toLowerCase() + 's';
			}
			if (!_model.id || _model.ownDetail == 0 || _model.twigDetail == '') {
				_model.twigDetail = val.toLowerCase();
			}
		}
		_model[attr] = val;
		repaint();
	};
</script>
{% endblock %}
